function tab1Init() {
}

function tab1ReClick() {
    if (_tab1.type == "fav") {
        _tab1.curpage = _tab1.cur_f_page;
        _tab1.pagescount = _tab1.pages_f_count;
    }
    else {
        _tab1.curpage = _tab1.cur_s_page;
        _tab1.pagescount = _tab1.pages_s_count;
    }
    ActivateTab1();
}

function ActivateTab1() {
    if (_tab1.type == "fav") {
        $('#searchp').css('display', 'none');
        $('#SearchInfo').css('display', 'none');
    }
    else {
        $('#searchp').css('display', 'block');
        $('#SearchInfo').css('display', 'block');
        if (_user.uid == "0") {
            $('#Exttab1Name').detach();
        }
        setOldParam();
    }
    PageClick(_tab1.curpage);
}

function SaveParams() {
    $.cookie(_user.uid + '_' + _general.lang + '_p0', (_tab1.params.p0) ? _tab1.params.p0 : "nil", { expires: 7 });
    $.cookie(_user.uid + '_' + _general.lang + '_p1', (_tab1.params.p1) ? _tab1.params.p1 : "nil", { expires: 7 });
    $.cookie(_user.uid + '_' + _general.lang + '_p2', (_tab1.params.p2) ? _tab1.params.p2 : "nil", { expires: 7 });
    $.cookie(_user.uid + '_' + _general.lang + '_p3', (_tab1.params.p3) ? _tab1.params.p3 : "nil", { expires: 7 });
    $.cookie(_user.uid + '_' + _general.lang + '_p4', (_tab1.params.p4) ? _tab1.params.p4 : "nil", { expires: 7 });
    $.cookie(_user.uid + '_' + _general.lang + '_p5', (_tab1.params.p5) ? _tab1.params.p5 : "nil", { expires: 7 });
    $.cookie(_user.uid + '_' + _general.lang + '_p6', (_tab1.params.p6) ? _tab1.params.p6 : "nil", { expires: 7 });
}

function GetParams() {
    if (!_tab1.params.used || _tab1.params.used == 0) {
        for (var i = 0; i < 7; i++) {
            var temp_param = $.cookie(_user.uid + '_' + _general.lang + '_p' + i);
            if (temp_param != null) {
                if (temp_param == 'nil') temp_param = '';
                eval(' _tab1.params.p' + i + '= "' + temp_param + '";');
                _tab1.params.loaded++;
            }
        }
    }
}

function setOldParam() {
    GetParams();
    if (!_tab1.params.loaded || _tab1.params.loaded == 0) {
        setFirstParam();
    }
    else {
        var str = '#Location_Tab1_Option option:[value="' + _tab1.params.p0 + '"]';
        $(str).attr('selected', 'selected');

        str = '#Age_From_Tab1_Option option:[value="' + _tab1.params.p1 + '"]';
        $(str).attr('selected', 'selected');

        str = '#Age_To_Tab1_Option option:[value="' + _tab1.params.p2 + '"]';
        $(str).attr('selected', 'selected');

        str = '#Gender_Tab1_Option option:[value="' + _tab1.params.p3 + '"]';
        $(str).attr('selected', 'selected');

        str = '#Status_Tab1_Option option:[value="' + _tab1.params.p4 + '"]';
        $(str).attr('selected', 'selected');

        str = '#LookingFor_Tab1_Option option:[value="' + _tab1.params.p5 + '"]';
        $(str).attr('selected', 'selected');

        str = '#Gender_Looking_Tab1_Option option:[value="' + _tab1.params.p6 + '"]';
        $(str).attr('selected', 'selected');
    }
}

function setFirstParam() {
    if (_user.birthday) {
        _user.age = getAge(_user.birthday);
    }
    if (_user.gender) {
        if (_user.gender == 'boy') _tab1.params.p3 = 'girl';
        else _tab1.params.p3 = 'boy';
        str = '#Gender_Tab1_Option option:[value="' + _tab1.params.p3 + '"]';
        $(str).attr('selected', 'selected');
    }
    if (_user.age) {
        _tab1.params.p1 = parseInt(_user.age) - 5;
        _tab1.params.p2 = parseInt(_user.age) + 5;

        var list = document.getElementById('Age_From_Tab1_Option');
        var i = 1;
        var delta = 100;
        var num = 0;
        while (i < list.options.length) {
            var temp = parseInt(list.options[i].value.substr(0, 2));
            if (Math.abs(temp - _tab1.params.p1) < delta) {
                delta = Math.abs(temp - _tab1.params.p1);
                num = i;
            }
            i++;
        }
        num = list.options[num].value;
        _tab1.params.p1 = num;
        str = '#Age_From_Tab1_Option option:[value="' + num + '"]';
        $(str).attr('selected', 'selected');

        list = document.getElementById('Age_To_Tab1_Option');
        i = 1;
        delta = 100;
        num = 0;
        while (i < list.options.length) {
            var temp = parseInt(list.options[i].value.substr(0, 2));
            if (Math.abs(temp - _tab1.params.p2) < delta) {
                delta = Math.abs(temp - _tab1.params.p2);
                num = i;
            }
            i++;
        }
        num = list.options[num].value;
        _tab1.params.p2 = num;
        str = '#Age_To_Tab1_Option option:[value="' + num + '"]';
        $(str).attr('selected', 'selected');
    }
}

//click on the page
function PageClick(id) {
    var need = true;
    if (id < 1) {
        id = 1;
        need = false;
    }
    if (_tab1.pagescount && id > _tab1.pagescount) {
        id = _tab1.pagescount;
        need = false;
    }
    _tab1.curpage = parseInt(id);
    if (_tab1.type == 'fav') _tab1.cur_f_page = _tab1.curpage;
    else _tab1.cur_s_page = _tab1.curpage;

    if (need) {
        DrawPages(_tab1.curpage);

        var array = [];
        if (_tab1.type == 'fav') {
            array = _tab1.favors;
        }
        else {
            array = _tab1.searched;
        }

        if (array[_tab1.curpage - 1]) {
            DisplaySix();
        }
        else GetSix(_tab1.curpage);
    }
}

//set fast pages
function setFastPages(curpage) {
    if (curpage == 1) {
        //$('#FirstPage').attr('className', 'fastpage');
        $('#PrevPage').css('cursor', 'default');
    }
    else {
        //$('#FirstPage').attr('className', 'fastpageactive')
        $('#PrevPage').css('cursor', 'pointer')
    }
    if (curpage == _tab1.pagescount) {
        //$('#LastPage').attr('className', 'fastpage');
        $('#NextPage').css('cursor', 'default');
    }
    else {
        //$('#LastPage').attr('className', 'fastpageactive')
        $('#NextPage').css('cursor', 'pointer')
    }
}

//get six persons for board
function GetSix(page) {
    $('#LUsers').html('');
    $('#RUsers').html('');
    $('#RUsers')
        .attr('align', 'left')
        .append(getLoader());
    var link = _general.link + "post_data.axd?type=get_six";
    var date;
    if (_tab1.searched[0] && _tab1.searched[0][0]) date = _tab1.searched[0][0].last_visit;
    $.post(link, {
        id: _user.uid,
        page: page,
        type: _tab1.type,
        param1: _tab1.params.p0,
        param2: _tab1.params.p1,
        param21: _tab1.params.p2,
        param3: _tab1.params.p3,
        param4: _tab1.params.p4,
        param5: _tab1.params.p5,
        param6: _tab1.params.p6,
        date: date
    }, function (result) { ParsingAnswerSix(result); }).error(function () { setTimeout(function () { GetSix(page); }, 1000); });
}

//return div with loader gif
function getLoader() {
    return $('<img/>')
        .attr('alt', '')
        .attr('src', _general.link + 'Images/loader.gif')
        .css('position', 'relative')
        .css('top', '180px')
        .css('left', '0px');
}

function ParsingAnswerSix(result) {
    if (result && result.data) {
        var array = [];
        if (_tab1.type == 'fav') {
            array = _tab1.favors;
            _tab1.favors_count = result.total;
        }
        else {
            array = _tab1.searched;
            _tab1.searched_count = result.total;
        }

        for (var i = 0; i < result.data.length; i++) {
            var p_num = parseInt(i / 6, 10) + _tab1.curpage - 1;
            var m_num = parseInt(i / 6, 10);
            if (!array[p_num]) array[p_num] = [];
            if (array[p_num].length <= (i - (m_num * 6))) {
                array[p_num].push(result.data[i]);
            }
        }
        DisplaySix();
    }
    else {
        $('#RUsers').attr('innerHTML', '');
        _tab1.curpage = 1;
        _tab1.pagescount = 1;
        DrawPages(_tab1.curpage);
    }
}

//display info about six persons
function DisplaySix() {
    var array = [], total, searched;
    if (_tab1.type == 'fav') {
        array = _tab1.favors;
        searched = _tab1.favors_count;
    }
    else {
        array = _tab1.searched;
        total = _tab1.total;
        searched = _tab1.searched_count;
    }

    if (searched % 6 > 0) _tab1.pagescount = parseInt(searched / 6, 10) + 1;
    else _tab1.pagescount = parseInt(searched / 6, 10);
    if (_tab1.type == 'fav') _tab1.pages_f_count = _tab1.pagescount;
    else _tab1.pages_s_count = _tab1.pagescount;

    $('#BoardY').attr('innerHTML', total);
    $('#BoardX').attr('innerHTML', searched);

    $('#LUsers').attr('innerHTML', '');
    $('#RUsers').attr('innerHTML', '');
    $('#RUsers').attr('align', 'right');
    var page_with_users = _tab1.curpage - 1;
    if (array[page_with_users]) {
        for (var i = 0; i < 6; i++) {
            if (array[page_with_users][i]) {
                var div = createUserInfoDiv(array[page_with_users][i]);
                if (i < 3) $('#LUsers').append(div);
                else $('#RUsers').append(div);
            }
        }
    }
    DrawPages(_tab1.curpage);
}

//make div with user info
function createUserInfoDiv(user) {
    var gender;
    var location = "";
    gender = user.gender;
    if (user.location) {
        location = user.location;
    }
    var like_text, like_img;
    if (user.liked == "0") {
        like_text = "LikeUser";
        like_img = 'images/like_user.png?ver=1';
    }
    else {
        like_text = "Invite";
        like_img = 'images/visitors.png?ver=1';
    }
    var likediv = $('<div/>')
        .attr('className', 'usertexticon')
        .attr('id', 'like_user_' + user.uid)
        .append($('<div/>')
            .css('width', '115px')
            .css('float', 'left')
            .attr('innerHTML', like_text)
        )
        .append($('<div/>')
            .css('width', '25px')
            .css('float', 'left')
            .attr('align', 'center')
            .append($('<img/>')
                .attr('alt', '')
                .attr('src', like_img)
            )
        )
        .click(function () {
            if (user.liked == "0") LikeUser(this.parentNode.id.split('_'), AfterLikeUser, 'like');
            else UserSelected(this.parentNode.id.split('_'));
        });

    return $('<table/>')
        .attr('className', 'user')
        .attr('cellPadding', '0')
        .attr('cellSpacing', '0')
        .append($('<tbody/>')
            .append($('<tr/>')
                .append($('<td/>')
                    .append($('<div/>')
                        .attr('id', 'img_' + user.uid + "_" + user.ufname)
                        .attr('className', 'userimg')
                        .attr('align', 'left')
                        .attr('dir', 'ltr')
                        .append($('<img/>')
                            .attr('alt', '')
                            .load(function () { $(this).unbind('load'); changeImg(this, 32, 32) })
                            .attr('src', user.picture)
                            .css('position', 'relative')
                            .click(function () { UserSelected(this.parentNode.id.split('_')); })
                        )
                        .mouseover(function () {
                            $('#text_' + user.uid + "_" + user.ufname)
                                .css('height', '20px')
                                .css('top', '-24px')
                        })
                        .mouseout(function () {
                            $('#text_' + user.uid + "_" + user.ufname)
                                .css('height', '1px')
                                .css('top', '0px')
                        })
                    )
                )
                .append($('<td/>')
                    .append($('<div/>')
                        .attr('id', "user_" + user.uid + "_" + user.ufname)
                        .css('float', 'left')
                        .css('width', '140px')
                        .append($('<div/>')
                            .attr('className', 'usertext')
                            .css('font-size', '14px')
                            .attr('innerHTML', user.ufname)
                        )
                        .append($('<div/>')
                            .attr('className', 'usertext')
                            .attr('innerHTML', gender)
                        )
                        .append($('<div/>')
                            .attr('className', 'usertext')
                            .attr('innerHTML', (user.age) ? user.age : '&nbsp;')
                        )
                        .append($('<div/>')
                            .attr('className', 'usertext')
                            .attr('innerHTML', location)
                        )
                        .append(likediv)
                        .append($('<div/>')
                            .attr('className', 'usertexticon')
                            .append($('<div/>')
                                .css('width', '115px')
                                .css('float', 'left')
                                .attr('innerHTML', "SendMessage")
                            )
                            .append($('<div/>')
                                .css('width', '25px')
                                .css('float', 'left')
                                .attr('align', 'center')
                                .append($('<img/>')
                                    .attr('alt', '')
                                    .attr('src', 'images/invite.png?ver=1')
                                )
                            )
                            .click(function () { showMessageForm(this.parentNode.id.split('_')[1]); })
                        )
                        .append($('<div/>')
                            .attr('className', 'usertexticon')
                            .attr('id', 'add_fav_' + user.uid)
                            .append($('<div/>')
                                .css('width', '115px')
                                .css('float', 'left')
                                .attr('innerHTML', (_tab1.type == "fav" || user.favored == "1") ? "DelFavorite" : "AddFavorite")
                            )
                            .append($('<div/>')
                                .css('width', '25px')
                                .css('float', 'left')
                                .attr('align', 'center')
                                .append($('<img/>')
                                    .attr('alt', '')
                                    .attr('src', 'images/staradd.png?ver=1')
                                )
                            )
                            .click(function () {
                                if (_tab1.type == "fav") {
                                    DelFromFavor(this.parentNode.id.split('_'), function () { GetSix(_tab1.curpage); });
                                }
                                else {
                                    if (user.favored == "1") DelFromFavor(this.parentNode.id.split('_'), AfterDelFavor);
                                    else AddToFavor(this.parentNode.id.split('_'), AfterAddFavor);
                                }
                            })
                        )
                    )
                )
            )
            .append($('<tr/>')
                .append($('<td/>')
                    .append($('<div/>')
                        .attr('className', 'userovericon')
                        .attr('id', 'text_' + user.uid + "_" + user.ufname)
                        .attr('align', 'right')
                        .mouseover(function () {
                            $('#text_' + user.uid + "_" + user.ufname)
                                .css('height', '20px')
                                .css('top', '-24px')
                        })
                        .mouseout(function () {
                            $('#text_' + user.uid + "_" + user.ufname)
                                .css('height', '1px')
                                .css('top', '0px')
                        })
                        .append($('<div/>')
                            .css('float', 'left')
                            .css('width', '71px')
                            .css('position', 'relative')
                            .css('top', '2px')
                            .attr('innerHTML', "Invite")
                        )
                        .append($('<div/>')
                            .attr('align', 'center')
                            .css('float', 'left')
                            .css('width', '22px')
                            .css('position', 'relative')
                            .css('top', '2px')
                            .append($('<img/>')
                                .attr('alt', '')
                                .attr('src', 'images/visitors.png?ver=1')
                            )
                        )
                        .click(function () { UserSelected(this.id.split('_')); })
                    )
                )
                .append($('<td/>').html('&nbsp'))
            )
        )
}

//change size of img
function changeImg(image, res_w, res_h) {
	var img = new Image();
	img.src = image.src;
	var width = img.width;
	var height = img.height;
	var attr, value, h, w, delta;
	if(width < height) {
		h = (height * res_w) / width;
		if(h < res_h) {
			h = res_h;
		}
		w = res_w;
	}
	else {
		w = (width * res_h) / height;
		if(w < res_w) {
			w = res_w;
		}
		h = res_h;
	}
	if(w < h) {
		delta = Math.abs((res_h - h) / 2);
	}
	else {
		delta = Math.abs((res_w - w) / 2);
	}
	image.style.height = h + "px";
	image.style.width = w + "px";
	if(delta != 0) {
		if(w > h) image.style.left = "-" + delta.toString() + "px";
		//else image.style.top = "-" + delta.toString() + "px";
	}
}


function AfterAddFavor(data) {
    var str = '#add_fav_' + data;
    $(str).unbind('click');
    $(str).click(function () { DelFromFavor(["", data], AfterDelFavor); });
    var div = document.getElementById('add_fav_' + data).childNodes[0];
    $(div).attr('innerHTML', "DelFavorite");
}

function AfterDelFavor(data) {
    var str = '#add_fav_' + data;
    $(str).unbind('click');
    $(str).click(function () { AddToFavor(["", data], AfterAddFavor); });
    var div = document.getElementById('add_fav_' + data).childNodes[0];
    $(div).attr('innerHTML', "AddFavorite");
}

function AfterLikeUser(id) {
    var str = '#like_user_' + id;
    $(str).unbind('click');
    $(str).click(function () { UserSelected(["", id]); });
    var div = document.getElementById('like_user_' + id).childNodes[0];
    $(div).attr('innerHTML', "Invite");
    div = document.getElementById('like_user_' + id).childNodes[1].childNodes[0];
    $(div).attr('src', 'images/visitors.png?ver=1');
}

//load photo to div
function loadPhoto(id, src) {
    var img = new Image();
    img.onload = function () {
        changeImg(id, src, this.width, this.height);
    };
    img.src = src;
}

//display pages
function DrawPages(curpage) {
    if (_tab1.pagescount >= curpage) {
        if (curpage > 0) {
            var pagesnum = 10;
            var width = 17;

            $('#PagesNums').attr("innerHTML", "");

            if (_tab1.pagescount > 10) {
                $('#PagesNums').append(createPageDiv((curpage == 1) ? 'sel' : '', 1));

                if (curpage > 4 && curpage < _tab1.pagescount - 3) {
                    $('#PagesNums').append(createPageDiv('', '...'));
                    for (var i = curpage - 2; i < curpage + 3; i++) {
                        $('#PagesNums').append(createPageDiv((i == curpage) ? 'sel' : '', i));
                    }
                    $('#PagesNums').append(createPageDiv('', '...'));
                }
                else {
                    if (curpage > _tab1.pagescount - 4) {
                        $('#PagesNums').append(createPageDiv('', '...'));
                        for (var i = _tab1.pagescount - 4; i < _tab1.pagescount; i++) {
                            $('#PagesNums').append(createPageDiv((i == curpage) ? 'sel' : '', i));
                        }
                    }
                    else {
                        for (var i = 2; i < 6; i++) {
                            $('#PagesNums').append(createPageDiv((i == curpage) ? 'sel' : '', i));
                        }
                        $('#PagesNums').append(createPageDiv('', '...'));
                    }
                }

                $('#PagesNums').append(createPageDiv((curpage == _tab1.pagescount) ? 'sel' : '', _tab1.pagescount));  
            }
            else {
                for (var i = 1; i < _tab1.pagescount + 1; i++) {
                    $('#PagesNums').append(createPageDiv((i == curpage) ? 'sel' : '', i));   
                }
            }   
            
            setFastPages(curpage);
        }
    }
}

function createPageDiv(type, num) {
    var width = 17;
    if (num != '...' && num > 99) width = 28;
    var  result =  $('<div/>')
        .attr('id', 'page_' + num)
        .attr('className', 'pagenum' + type)
        .css('width', width + 'px')
        .attr('align', 'right')
        .append($('<div/>')
            .attr('id', 'page_' + num)
            .attr('className', 'pagenum' + type + '_start')
            .css('width', width - 5 + "px")
            .html(num)
        )
        .append($('<div/>')
            .attr('id', 'page_' + num)
            .attr('className', 'pagenum' + type + '_end')
        )

    if (num != '...')  result.click(function () { PageClick(num); })

    return result;
}

function ChangeSearchParams() {
    RefreshBanner();
    if ($('#Location_Tab1_Option').attr('value') != null) _tab1.params.p0 = $('#Location_Tab1_Option').attr('value');
    if ($('#Age_From_Tab1_Option').attr('value') != null) _tab1.params.p1 = $('#Age_From_Tab1_Option').attr('value');
    if ($('#Age_To_Tab1_Option').attr('value') != null) _tab1.params.p2 = $('#Age_To_Tab1_Option').attr('value');
    if ($('#Gender_Tab1_Option').attr('value') != null) _tab1.params.p3 = $('#Gender_Tab1_Option').attr('value');
    if ($('#Status_Tab1_Option').attr('value') != null) _tab1.params.p4 = $('#Status_Tab1_Option').attr('value');
    if ($('#LookingFor_Tab1_Option').attr('value') != null) _tab1.params.p5 = $('#LookingFor_Tab1_Option').attr('value');
    if ($('#Gender_Looking_Tab1_Option').attr('value') != null) _tab1.params.p6 = $('#Gender_Looking_Tab1_Option').attr('value');
    SaveParams();
    clearGettedUsers();
    _tab1.curpage = 1;
    GetSix(_tab1.curpage);
}

function clearGettedUsers() {
    if (_tab1.searched && _tab1.searched.length > 0) _tab1.searched.splice(0, _tab1.searched.length);
}

function ShowExtended() {
    var div = document.getElementById('ExtSearch');
    if (div.offsetHeight == 1) {
        div.style.height = '28px';
        div.style.width = '445px';
    }
    else {
        div.style.height = '1px';
        div.style.width = '1px';
    }
}

function LikeUser(id, callback, like) {
    if (!_user.uid || _user.uid == "0") showUserInfoForm();
    else {
        if (like == 'like') {
            for (var i = 0; i < _tab1.searched.length; i++) {
                if (_tab1.searched[i] && _tab1.searched[i].length > 0)
                    for (var j = 0; j < _tab1.searched[i].length; j++) {
                        if (_tab1.searched[i][j].uid == id[1]) {
                            _tab1.searched[i][j].liked = "1";
                            break;
                        }
                    }
            }
        }

        var link = _general.link + "post_data.axd?type=add_visitor"
        $.post(link, {
            id: _user.uid,
            toid: id[1],
            like: like
        }, function (res) {
            if (res && res.data) {
                if (res.data.need == '1') {
                    increment(res.data.fbid, res.data.token);
                }
            }
            if (callback) callback(id[1]);
        }).error(function () { setTimeout(function () { LikeUser(id, callback, like); }, 1000); }); ;
    }
}

function delFromFavUsers(id) {
    for (var i = 0; i < _tab1.favors.length; i++) {
        for (var j = 0; j < _tab1.favors[i].length; j++) {
            if (_tab1.favors[i][j].uid == id) {
                _tab1.favors[i].splice(j, 1);
                break;
            }
        }
    }
}
//add to favorite
function AddToFavor(id, callback) {
    if (_user.uid == "0") showUserInfoForm();
    else {
        for (var i = 0; i < _tab1.searched.length; i++) {
            if (_tab1.searched[i] && _tab1.searched[i].length > 0)
                for (var j = 0; j < _tab1.searched[i].length; j++) {
                    if (_tab1.searched[i][j].uid == id[1]) {
                        _tab1.favors.splice(0, _tab1.favors.length);
                        _tab1.searched[i][j].favored = "1";
                        break;
                    }
                }
        }
        var link = _general.link + "post_data.axd?type=add_favor"
        $.post(link, {
            id: _user.uid,
            toid: id[1]
        }, function (data) {
            LikeUser(id, null, 'like');
            if (callback) callback(id[1]);
        }).error(function () { setTimeout(function () { AddToFavor(id, callback); }, 1000); });
    }
}

//add to favorite
function DelFromFavor(id, callback) {
    for (var i = 0; i < _tab1.searched.length; i++) {
        if (_tab1.searched[i] && _tab1.searched[i].length > 0) {
            for (var j = 0; j < _tab1.searched[i].length; j++) {
                if (_tab1.searched[i][j].uid == id[1]) {
                    delFromFavUsers(id[1]);
                    _tab1.searched[i][j].favored = "-1";
                    break;
                }
            }
        }
    }
    _tab1.favors.splice(0, _tab1.favors.length);

    var link = _general.link + "post_data.axd?type=del_favor"
    $.post(link, {
        id: _user.uid,
        toid: id[1]
    }, function (data) { if (callback) callback(id[1]); }).error(function () { setTimeout(function () { DelFromFavor(id, callback); }, 1000); }); ;
}